#include "settings.h"
#include "ui_settings.h"

Settings::Settings(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Setttings),
    m_default_bell_music_path(":/pics/alarm.wav")
{

    ui->setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose,true);
    // 禁止调整窗口大小
    setFixedSize(this->width(), this->height());
    this->setWindowIcon(QIcon(":/pics/trayico"));
    this->setWindowTitle("设置");
    QDir dir;

//    bell_music_path = QDir::fromNativeSeparators(dir.absoluteFilePath("./bellMusic"));
    m_bell_music_path = QString("%1/%2").arg(QDir::fromNativeSeparators(QApplication::applicationDirPath())).arg("bellMusic");
    //    组件设置初始值
    ui->work_time->setValue((int)taskItem::config->m_tomatoTime/60);
    ui->rest_time->setValue((int)taskItem::config->m_tomatoTime_rest/60);
    ui->bell_loop->setValue(taskItem::config->m_bellLoop);

    //初始化具有自定义数据的comboBox
        //QMap自动根据 key排序
    QMap<QString, QString> sortItem;
    sortItem.insert("隐藏","hidden");
    sortItem.insert("删除","delete");

    ui->finished_task->clear();
    foreach(const QString &str,sortItem.keys())
        ui->finished_task->addItem(str,sortItem.value(str));


    if (taskItem::config->m_finishedTask == "hidden")
        ui->finished_task->setCurrentText("隐藏");
    else
        ui->finished_task->setCurrentText("删除");

    // 初始化铃音下拉框
    loadBellMusic();
    connect(ui->bell, &QComboBox::currentTextChanged, this, &Settings::bellChanged);

    // 计时器到期提示音
    m_timer_end_effect = new QSoundEffect;
    m_timer_end_effect->setSource(QUrl::fromLocalFile(taskItem::config->m_bellCurrent));
    m_timer_end_effect->setLoopCount(taskItem::config->m_bellLoop);
    m_timer_end_effect->setVolume(0.7f);

    // 服务器地址
    ui->serverAddressEdit->setText(taskItem::config->m_serverAddress);

    if (taskItem::config->m_closeAndMinimize)
        ui->closeMin->setChecked(true);
    else
        ui->closeMin->setChecked(false);


    if (isAppAutoRun())
        ui->autoRun->setChecked(true);
    else
        ui->autoRun->setChecked(false);
    // 默认描述文本
    ui->taskDescribe->setPlainText(taskItem::config->m_defaultDescribe);




}

Settings::~Settings()
{
    delete ui;
    delete m_timer_end_effect;
}

void Settings::loadBellMusic()
{


    if (!checkDirExist(m_bell_music_path))
    {
        qDebug() << "bell music path init failed " ;
    }

    sPairVector *files_info = getFileListUnderDir(m_bell_music_path, "wav");


    ui->bell->clear();
    ui->bell->addItem("default", m_default_bell_music_path);

    QString currText;
    qDebug() << "bellCrrent " << taskItem::config->m_bellCurrent;
    foreach(const sPair &pair,*files_info)
    {
        qDebug() << "pair " << pair.second;
        if (pair.second == taskItem::config->m_bellCurrent) currText = pair.first;
        ui->bell->addItem(pair.first,pair.second);
    }

    ui->bell->setCurrentText(currText);





}

bool Settings::checkDirExist(QString path)
{


    QDir dir(path);
    if (!dir.isAbsolute()) path = dir.absolutePath();
    if(dir.exists())
    {
      return true;
    }
    else
    {
       bool ok = dir.mkdir(path);//只创建一级子目录，即必须保证上级目录存在
       return ok;
    }
}

void Settings::on_pushButton_clicked()
{
    int work_time = ui->work_time->value();
    int rest_time = ui->rest_time->value();
    QString finishedTask = ui->finished_task->currentData().toString();
    QString bellCurrent = ui->bell->currentData().toString();
    int bellLoop = ui->bell_loop->value();

    taskItem::config->m_tomatoTime = work_time*60;
    taskItem::config->m_tomatoTime_rest = rest_time*60;
    taskItem::config->m_finishedTask = finishedTask;
    taskItem::config->m_bellCurrent = bellCurrent;
    taskItem::config->m_bellLoop = bellLoop;
    taskItem::config->m_serverAddress = ui->serverAddressEdit->text();
    taskItem::config->m_closeAndMinimize = ui->closeMin->isChecked();
    taskItem::config->m_autoRun = ui->autoRun->isChecked();
    taskItem::config->m_defaultDescribe = ui->taskDescribe->toPlainText();


    setAppAutoRun(taskItem::config->m_autoRun);
    taskItem::configfile->save();

    emit doSettings();
    close();



}

void Settings::on_pushButton_2_clicked()
{
    close();
}

void Settings::on_import_bell_clicked()
{
    QStringList fileNames = QFileDialog::getOpenFileNames(this, "设置铃声",".","*.wav");
    foreach(const QString &fileName, fileNames)
    {
        if (fileName.isEmpty()) continue;

        QFileInfo fileInfo(fileName);
        QString dstDir = m_bell_music_path;
        if (!dstDir.endsWith(QDir::separator())) dstDir += '/';
        QString dstFileName = dstDir + fileInfo.fileName();
        if (QFile::exists(dstFileName))
        {
            QMessageBox::warning(this, "警告", QString("目标文件 %1\n已存在!").arg(dstFileName),"确定");
            continue;
        }
        QFile::copy(fileName, dstFileName);
    }

    loadBellMusic();
}

sPairVector* Settings::getFileListUnderDir(QString dirName, QString type)
{
    sPairVector *spair_vector = new sPairVector;
    type = type.toLower();

    QDir dir(dirName);

    QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Dirs);
    foreach (auto &fileInfo , fileInfoList)
    {

        if (fileInfo.isDir())
        {
            *spair_vector = *spair_vector + *getFileListUnderDir(fileInfo.absoluteFilePath(), type);
        } else if (fileInfo.isFile())
        {

            if (fileInfo.suffix().toLower() == type)
            {
                spair_vector->push_back(sPair(fileInfo.fileName(), fileInfo.absoluteFilePath()));
            }

        }
    }
    return spair_vector;

}

void Settings::bellChanged()
{
    QString path = ui->bell->currentData().toString();
    int loop = 1;
    m_timer_end_effect->setSource(QUrl::fromLocalFile(path));
    m_timer_end_effect->setLoopCount(loop);
    m_timer_end_effect->setVolume(0.7f);
    m_timer_end_effect->play();
}

void Settings::setAppAutoRun(bool isStart)
{
    QString autoRunBatPath;
    if ((autoRunBatPath = checkAutoRunBat()).isEmpty()) return;


    QString application_name = QApplication::applicationName();
    QSettings settings(AUTO_RUN_KEY,QSettings::NativeFormat);
    if (isStart)
    {
        settings.setValue(application_name, QDir::toNativeSeparators(autoRunBatPath));
    } else
    {
        settings.remove(application_name);
    }
}

bool Settings::isAppAutoRun()
{
    QString autoRunBatPath;
    if ((autoRunBatPath = checkAutoRunBat()).isEmpty()) return false;

    QString application_name = QApplication::applicationName();
    QSettings settings(AUTO_RUN_KEY,QSettings::NativeFormat);
    return settings.value(application_name).toString() == QDir::toNativeSeparators(autoRunBatPath);
}

QString Settings::checkAutoRunBat()
{
    QDir dir(QApplication::applicationDirPath());
    QString autoRunBatPath = dir.absoluteFilePath(AUTO_RUN_BAT);

    if (!QFile::exists(autoRunBatPath))
    {
        QFile autoRunBat(autoRunBatPath);
        if (!autoRunBat.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            qDebug() << autoRunBatPath << " file open error";
            return "";
        }

        QString autoRunFileContent = QString("@echo off\ncd /d %~dp0\nstart \"\" \"%1.exe\"\nexit").arg(QApplication::applicationName());
        QByteArray byteArr = autoRunFileContent.toUtf8();
        autoRunBat.write(byteArr, byteArr.length());
        autoRunBat.close();
    }
    return autoRunBatPath;
}
